<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>手写签名</title>
</head>

<body>
  <canvas id="signature" width="800" height="600"></canvas>
  <button id="save">保存签名</button>
  <button id="clear">重新签名</button>
  <script>
    var canvas = document.getElementById("signature");
    var ctx = canvas.getContext("2d");
    ctx.strokeStyle = "black";
    ctx.lineWidth = 4;
    ctx.lineCap = "round";
    ctx.lineJoin = "round";
    var isDrawing = false;
    var lastX = 0;
    var lastY = 0;

    canvas.addEventListener("mousedown", function (e) {
      isDrawing = true;
      lastX = e.offsetX;
      lastY = e.offsetY;
    });

    canvas.addEventListener("mousemove", function (e) {
      if (isDrawing) {
        ctx.beginPath();
        ctx.moveTo(lastX, lastY);
        ctx.lineTo(e.offsetX, e.offsetY);
        ctx.stroke();
        lastX = e.offsetX;
        lastY = e.offsetY;
      }
    });

    canvas.addEventListener("mouseup", function (e) {
      isDrawing = false;
    });
    // 重新签名
    document.getElementById("clear").addEventListener("click", function () {
      ctx.clearRect(0, 0, canvas.width, canvas.height);
    });
    // 保存签名
    document.getElementById("save").addEventListener("click", function () {
      var dataURL = canvas.toDataURL();
      console.log(dataURL);

      // // 上传给后台
      // var xhr = new XMLHttpRequest();
      // xhr.open("POST", "your_server_url", true);
      // xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
      // xhr.send("image=" + encodeURIComponent(dataURL));
    });
  </script>
</body>

</html>